package com.example.blog.util.PcUtils;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
public class HeaderFileUtils {
    @Data
    public static class HeaderResult {
        private File Headerfile;

        private String url;
    }


    public static File getUploadDir(HttpServletRequest request){
        File rootDir = new File(System.getProperty("user.dir"));
        File uploadDir = new File(rootDir, "header");
        if (!uploadDir.exists()) {
            log.info("创建父目录 => " + uploadDir);
            uploadDir.mkdirs();
        }
        return uploadDir;
    }

    public static File getHearderFile(HttpServletRequest request,String fileName) {
        File uploadDir = getUploadDir(request);
        return new File(uploadDir,fileName);
    }
    public static HeaderFileUtils.HeaderResult savePart(HttpServletRequest request, Part HeaderfilePart) throws IOException {
        HeaderFileUtils.HeaderResult result = new HeaderFileUtils.HeaderResult();
        String fileName = getPrefix() + "_" + getFileName(HeaderfilePart);
        // 创建存储目录（如果不存在）
        File uploadDir = getUploadDir(request);
        result.Headerfile = new File(uploadDir, fileName);
        log.info("保存文件 => " + result.Headerfile);
        HeaderfilePart.write(result.Headerfile.getAbsolutePath());
        // 生成页面访问url
        result.url = request.getContextPath() + "/headerFiles/" + fileName;
        return result;
    }

    private static String getPrefix() {
        return UUID.randomUUID().toString();
    }

    private static String getFileName(Part part) {
        String contentDisp = part.getHeader("content-disposition");
        String[] tokens = contentDisp.split(";");
        for (String token : tokens) {
            if (token.trim().startsWith("filename")) {
                return token.substring(token.indexOf("=") + 2, token.length() - 1);
            }
        }
        return "";
    }
}
